package models

import (
	"errors"
	"fmt"
	"ginstudydemo.com/main/dao"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"log"
	"strconv"
	"strings"
)

// GetVerifyUserInfo 根据用户名或手机号查询用户的基本验证信息（用户名、密码、手机号）
func GetVerifyUserInfo(query LoginRequest) (*GetVerifyUserInfoRes, error) {
	var result GetVerifyUserInfoRes

	// 根据用户名或手机号查询用户信息
	err := dao.Db.Debug().Table("users t1").
		Select("t1.id AS userId, t1.username, t1.password, t1.phone_number, t1.status").
		Where("t1.username = ? OR t1.phone_number = ? AND t1.is_deleted = ?", query.Username, query.Username, 0).
		Scan(&result).Error

	if err != nil {
		return nil, err
	}

	// 检查查询结果是否为空
	if result.UserID == 0 {
		// 如果 UserId 为 0，表示没有查询到数据
		return nil, fmt.Errorf("账号错误")
	}

	return &result, nil
}

// GetUserInfoById  根据用户ID从数据库中获取用户信息
func GetUserInfoById(id string) (*SysUserUsersMeSelect, error) {

	var result SysUserUsersMeSelect
	//SELECT id, username, nickname, avatar FROM sys_user
	//WHERE is_deleted = 0 AND (username = ?)
	err := dao.Db.Debug().Table("users").
		Select(`id AS userId, username, nickname, avatar, email, account_type, 
			phone_number, wechat_openid, qq_openid, huawei_id, status, last_login_time`).
		Where("is_deleted = 0 AND id = ?", id).
		Scan(&result).Error

	if err != nil {
		return nil, err
	}
	return &result, nil
}

// AddUserCollect 收藏资源
func AddUserCollect(query UserCollectParams) CollectStatus {
	// 开启事务
	tx := dao.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 检查是否已收藏
	var exist UserCollect
	err := tx.Debug().Where("user_id = ? AND resource_id = ? AND is_deleted = 0", query.UserID, query.ResourceID).First(&exist).Error
	if err == nil {
		tx.Rollback()
		return CollectStatusAlready
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		tx.Rollback()
		return CollectStatusError
	}

	// 检查是否有软删除的记录，如果有则恢复
	var deleted UserCollect
	err = tx.Debug().Where("user_id = ? AND resource_id = ? AND is_deleted = 1", query.UserID, query.ResourceID).First(&deleted).Error
	if err == nil {
		// 恢复收藏记录
		if err := tx.Debug().Model(&deleted).Updates(map[string]interface{}{
			"is_deleted":  0,
			"create_time": gorm.Expr("CURRENT_TIMESTAMP"),
		}).Error; err != nil {
			tx.Rollback()
			return CollectStatusError
		}

		// 增加资源收藏量
		if err := tx.Debug().Model(&Resource{}).
			Where("id = ?", query.ResourceID).
			Update("collect_count", gorm.Expr("collect_count + 1")).Error; err != nil {
			tx.Rollback()
			return CollectStatusError
		}

		tx.Commit()
		return CollectStatusSuccess
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		tx.Rollback()
		return CollectStatusError
	}

	// 新增收藏
	collect := UserCollect{
		UserID:     query.UserID,
		ResourceID: query.ResourceID,
	}
	if err := tx.Debug().Create(&collect).Error; err != nil {
		tx.Rollback()
		return CollectStatusError
	}

	// 增加资源收藏量
	if err := tx.Debug().Model(&Resource{}).
		Where("id = ?", query.ResourceID).
		Update("collect_count", gorm.Expr("collect_count + 1")).Error; err != nil {
		tx.Rollback()
		return CollectStatusError
	}

	tx.Commit()
	return CollectStatusSuccess
}

// CancelUserCollect 取消收藏资源
func CancelUserCollect(query UserCollectParams) CollectStatus {
	// 开启事务
	tx := dao.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 取消收藏
	result := tx.Debug().Model(&UserCollect{}).
		Where("user_id = ? AND resource_id = ? AND is_deleted = 0", query.UserID, query.ResourceID).
		Update("is_deleted", 1)

	if result.Error != nil {
		tx.Rollback()
		return CollectStatusError
	}

	// 检查是否真的有记录被更新
	if result.RowsAffected == 0 {
		tx.Rollback()
		return CollectStatusError
	}

	// 减少资源收藏量
	if err := tx.Debug().Model(&Resource{}).
		Where("id = ?", query.ResourceID).
		Update("collect_count", gorm.Expr("collect_count - 1")).Error; err != nil {
		tx.Rollback()
		return CollectStatusError
	}

	tx.Commit()
	return CollectStatusSuccess
}

// AddUserTopic 收藏专辑
func AddUserTopic(query UserTopicParams) CollectStatus {
	// 开启事务
	tx := dao.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 检查是否已收藏
	var exist UserTopic
	err := tx.Debug().Where("user_id = ? AND topic_id = ? AND is_deleted = 0", query.UserID, query.TopicID).First(&exist).Error
	if err == nil {
		tx.Rollback()
		return CollectStatusAlready
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		tx.Rollback()
		return CollectStatusError
	}

	// 检查是否有软删除的记录，如果有则恢复
	var deleted UserTopic
	err = tx.Debug().Where("user_id = ? AND topic_id = ? AND is_deleted = 1", query.UserID, query.TopicID).First(&deleted).Error
	if err == nil {
		// 恢复收藏记录
		if err := tx.Debug().Model(&deleted).Updates(map[string]interface{}{
			"is_deleted":  0,
			"create_time": gorm.Expr("CURRENT_TIMESTAMP"),
		}).Error; err != nil {
			tx.Rollback()
			return CollectStatusError
		}

		// 增加专辑收藏量
		if err := tx.Debug().Model(&Topic{}).
			Where("id = ?", query.TopicID).
			Update("collect_count", gorm.Expr("collect_count + 1")).Error; err != nil {
			tx.Rollback()
			return CollectStatusError
		}

		tx.Commit()
		return CollectStatusSuccess
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		tx.Rollback()
		return CollectStatusError
	}

	// 新增收藏
	collect := UserTopic{
		UserID:  query.UserID,
		TopicID: query.TopicID,
	}
	if err := tx.Debug().Create(&collect).Error; err != nil {
		tx.Rollback()
		return CollectStatusError
	}

	// 增加专辑收藏量
	if err := tx.Debug().Model(&Topic{}).
		Where("id = ?", query.TopicID).
		Update("collect_count", gorm.Expr("collect_count + 1")).Error; err != nil {
		tx.Rollback()
		return CollectStatusError
	}

	tx.Commit()
	return CollectStatusSuccess
}

// CancelUserTopic 取消收藏专辑
func CancelUserTopic(query UserTopicParams) CollectStatus {
	// 开启事务
	tx := dao.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 取消收藏
	result := tx.Debug().Model(&UserTopic{}).
		Where("user_id = ? AND topic_id = ? AND is_deleted = 0", query.UserID, query.TopicID).
		Update("is_deleted", 1)

	if result.Error != nil {
		tx.Rollback()
		return CollectStatusError
	}

	// 检查是否真的有记录被更新
	if result.RowsAffected == 0 {
		tx.Rollback()
		return CollectStatusCancel
	}

	// 减少专辑收藏量
	if err := tx.Debug().Model(&Topic{}).
		Where("id = ?", query.TopicID).
		Update("collect_count", gorm.Expr("collect_count - 1")).Error; err != nil {
		tx.Rollback()
		return CollectStatusError
	}

	tx.Commit()
	return CollectStatusCancel
}

// AddUserLike 用户点赞
func AddUserLike(query UserLikeRequestParam) UserLikeResStatus {
	// 开启事务
	tx := dao.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 验证目标类型
	if !query.TargetType.IsValid() {
		tx.Rollback()
		return UserLikeResStatusNoTargetType
	}

	// 检查是否已点赞
	var exist UserLike
	err := tx.Debug().Where("user_id = ? AND target_id = ? AND target_type = ? AND is_deleted = 0",
		query.UserID, query.TargetID, query.TargetType).First(&exist).Error
	if err == nil {
		tx.Rollback()
		return UserLikeResStatusAlready
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		tx.Rollback()
		return UserLikeResStatusError
	}

	// 检查是否有软删除的记录，如果有则恢复
	var deleted UserLike
	err = tx.Debug().Where("user_id = ? AND target_id = ? AND target_type = ? AND is_deleted = 1",
		query.UserID, query.TargetID, query.TargetType).First(&deleted).Error
	if err == nil {
		// 恢复点赞记录
		if err := tx.Debug().Model(&deleted).Updates(map[string]interface{}{
			"is_deleted":  0,
			"create_time": gorm.Expr("CURRENT_TIMESTAMP"),
		}).Error; err != nil {
			tx.Rollback()
			return UserLikeResStatusError
		}

		// 根据目标类型更新点赞数
		if err := updateLikeCount(tx, query.TargetType, query.TargetID, 1); err != nil {
			tx.Rollback()
			return UserLikeResStatusError
		}

		tx.Commit()
		return UserLikeResStatusSuccess
	}

	if !errors.Is(err, gorm.ErrRecordNotFound) {
		tx.Rollback()
		return UserLikeResStatusError
	}

	// 新增点赞
	like := UserLike{
		UserID:     query.UserID,
		TargetID:   query.TargetID,
		TargetType: query.TargetType,
	}
	if err := tx.Debug().Create(&like).Error; err != nil {
		tx.Rollback()
		return UserLikeResStatusError
	}

	// 根据目标类型更新点赞数
	if err := updateLikeCount(tx, query.TargetType, query.TargetID, 1); err != nil {
		tx.Rollback()
		return UserLikeResStatusError
	}

	tx.Commit()
	return UserLikeResStatusSuccess
}

// 更新点赞数辅助函数
func updateLikeCount(tx *gorm.DB, targetType LikeTargetType, targetID int64, delta int) error {
	switch targetType {
	case LikeTargetResource:
		return tx.Debug().Model(&Resource{}).
			Where("id = ?", targetID).
			Update("like_count", gorm.Expr("like_count + ?", delta)).Error
	case LikeTargetTopic:
		return tx.Debug().Model(&Topic{}).
			Where("id = ?", targetID).
			Update("like_count", gorm.Expr("like_count + ?", delta)).Error
	default:
		return fmt.Errorf("invalid target type")
	}
}

// CancelUserLike 取消用户点赞
func CancelUserLike(query UserLikeRequestParam) UserLikeResStatus {
	// 开启事务
	tx := dao.Db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 验证目标类型
	if !query.TargetType.IsValid() {
		tx.Rollback()
		return UserLikeResStatusNoTargetType
	}

	// 取消点赞
	result := tx.Debug().Model(&UserLike{}).
		Where("user_id = ? AND target_id = ? AND target_type = ? AND is_deleted = 0",
			query.UserID, query.TargetID, query.TargetType).
		Update("is_deleted", 1)

	if result.Error != nil {
		tx.Rollback()
		return UserLikeResStatusError
	}

	// 检查是否真的有记录被更新
	if result.RowsAffected == 0 {
		tx.Rollback()
		return UserLikeResStatusError
	}

	// 根据目标类型更新点赞数
	if err := updateLikeCount(tx, query.TargetType, query.TargetID, -1); err != nil {
		tx.Rollback()
		return UserLikeResStatusError
	}

	tx.Commit()
	return UserLikeResStatusSuccess
}

// GetUserCollectTopics 获取用户收藏的专题列表
func GetUserCollectTopics(req UserCollectTopicRequestParam, pageParams PaginationParams) ([]UserTopicRes, int64, int, int, error) {

	topics := make([]UserTopicRes, 0)

	var total int64

	// 验证用户ID
	if req.UserID == 0 {
		return nil, 0, 0, 0, errors.New("user id is required")
	}
	userID, err := strconv.ParseInt(strconv.FormatInt(req.UserID, 10), 10, 64)
	if err != nil {
		return nil, 0, 0, 0, fmt.Errorf("invalid user id: %v", err)
	}

	// 解析分页参数
	pageNum, _ := strconv.Atoi(strconv.Itoa(pageParams.PageNum))
	if pageNum <= 0 {
		pageNum = 1
	}
	pageSize, _ := strconv.Atoi(strconv.Itoa(pageParams.PageSize))
	if pageSize <= 0 {
		pageSize = 10
	}
	offset := (pageNum - 1) * pageSize

	// 构建查询
	query := dao.Db.Debug().Table("topic t").
		Select("t.*, tt.name as category_name").
		Joins("INNER JOIN user_topic ut ON t.id = ut.topic_id").
		Joins("LEFT JOIN topic_type tt ON t.category_id = tt.id").
		Where("ut.user_id = ? AND ut.is_deleted = 0 AND t.is_deleted = 0", userID)

	// 分类筛选
	if req.CategoryID != "" {
		categoryIDs := strings.Split(req.CategoryID, ",")
		query = query.Where("t.category_id IN ?", categoryIDs)
	}

	// 内容类型筛选
	if req.ContentType != "" {
		contentType, err := strconv.ParseInt(req.ContentType, 10, 8)
		if err == nil {
			query = query.Where("t.content_type = ?", contentType)
		}
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, 0, 0, err
	}

	// 分页查询
	err = query.Order("ut.create_time DESC").
		Offset(offset).
		Limit(pageSize).
		Scan(&topics).Error

	if err != nil {
		return nil, 0, 0, 0, err
	}

	return topics, total, pageParams.PageNum, pageParams.PageSize, nil

}

// GetUserResUsePageByCate 获取用户收藏的资源列表
func GetUserResUsePageByCate(query UserResourcePageByCateParams, pageParams PaginationParams) ([]UserResourceRes, int64, int, int, error) {
	resources := make([]UserResourceRes, 0)

	// 验证用户ID
	if query.UserID == "" {
		return nil, 0, 0, 0, errors.New("user id is required")
	}
	userID, err := strconv.ParseInt(query.UserID, 10, 64)
	if err != nil {
		return nil, 0, 0, 0, fmt.Errorf("invalid user id: %v", err)
	}

	model := dao.Db.Debug().Table("resource r").
		Select("r.*, ct.name as category_name, rt.name as resource_type_name,t.id as topic_id, t.title as topic_title,JSON_UNQUOTE(JSON_EXTRACT(r.tags, '$[*]')) as tags").
		Joins("INNER JOIN user_collect uc ON uc.resource_id = r.id").
		Joins("LEFT JOIN content_type ct ON r.category_id = ct.id").
		Joins("LEFT JOIN resource_type rt ON r.resource_type = rt.id").
		Joins("LEFT JOIN topic_resource tr ON r.id = tr.resource_id").
		Joins("LEFT JOIN topic t ON tr.topic_id = t.id").
		Where("uc.user_id = ? AND uc.is_deleted = 0 AND r.is_deleted = 0", userID)

	// 是否获取子集分类数据
	if query.IsSubCate {
		var flatCategories []CategoryAndResRecursionData
		categoryIDsRECURSIVE := strings.Split(query.CategoryID, ",")

		errRECURSIVE := dao.Db.Debug().Raw(`
        WITH RECURSIVE cte AS (
            SELECT * FROM content_type WHERE id IN ?
            UNION ALL
            SELECT c.* FROM content_type c
            INNER JOIN cte ON c.parent_id = cte.id
        )
        SELECT * FROM cte WHERE is_deleted = 0;
    `, categoryIDsRECURSIVE).Scan(&flatCategories).Error
		if errRECURSIVE != nil {
			return nil, 0, 0, 0, errRECURSIVE
		}

		if len(flatCategories) == 0 {
			return nil, 0, 0, 0, nil
		}

		var categoryIDs []int64
		for _, cat := range flatCategories {
			categoryIDs = append(categoryIDs, cat.ID)
		}

		strNums := make([]string, len(categoryIDs))
		for i, num := range categoryIDs {
			strNums[i] = strconv.Itoa(int(num))
		}

		fmt.Println("=== Final categoryIDs ===")
		fmt.Printf("Total IDs: %d\n", len(categoryIDs))
		fmt.Printf("IDs list: %v\n", categoryIDs)
		fmt.Println("=========================")

		categoryIDsStr := strings.Join(strNums, ",")

		if categoryIDsStr != "" {
			categoryIDs := strings.Split(categoryIDsStr, ",")
			model = model.Where("r.category_id IN ?", categoryIDs)
		}
	} else {
		if query.CategoryID != "" {
			fmt.Printf("IDs list: %s\n", query.CategoryID)

			categoryIDs := strings.Split(query.CategoryID, ",")
			model = model.Where("r.category_id IN ?", categoryIDs)
		}
	}

	// 资源类型筛选
	if query.ResourceType != "" {
		model = model.Where("r.resource_type = ?", query.ResourceType)
	}

	// 关键词筛选
	if query.Keyword != "" {
		// 绑定前打印原始查询参数
		log.Printf("关键词筛选关键词筛选关键词筛选关键词筛选关键词筛选:")

		model = model.Where("r.title LIKE ?", "%"+query.Keyword+"%")
	}

	// 获取总数
	var total int64
	if err := model.Count(&total).Error; err != nil {
		return nil, 0, 0, 0, err
	}

	// 添加分页条件
	offset := (pageParams.PageNum - 1) * pageParams.PageSize
	model = model.Limit(pageParams.PageSize).Offset(offset)

	// 执行查询获取分页数据
	if err := model.Scan(&resources).Error; err != nil {
		return resources, 0, 0, 0, err
	}

	return resources, total, pageParams.PageNum, pageParams.PageSize, nil
}

// UpdateUser 更新用户信息
func UpdateUser(userId int64, req UpdateUserRequestParam) (int64, error) {

	// 构建更新字段映射
	updateData := make(map[string]interface{})
	if req.Nickname != nil {
		updateData["nickname"] = *req.Nickname
	}
	if req.Avatar != nil {
		updateData["avatar"] = *req.Avatar
	}
	if req.Email != nil {
		updateData["email"] = *req.Email
	}
	if req.AccountType != nil {
		updateData["account_type"] = *req.AccountType
	}
	if req.Username != nil {
		updateData["username"] = *req.Username
	}
	if req.Password != nil {
		// 实际项目需要加密处理
		updateData["password"] = *req.Password
	}
	if req.PhoneNumber != nil {
		updateData["phone_number"] = *req.PhoneNumber
	}
	if req.WechatOpenID != nil {
		updateData["wechat_openid"] = *req.WechatOpenID
	}
	if req.QQOpenID != nil {
		updateData["qq_openid"] = *req.QQOpenID
	}
	if req.HuaweiID != nil {
		updateData["huawei_id"] = *req.HuaweiID
	}
	if req.Status != nil {
		updateData["status"] = *req.Status
	}

	// 没有需要更新的字段
	if len(updateData) == 0 {
		return 0, errors.New("没有需要更新的字段")
	}
	// 执行更新操作
	result := dao.Db.Debug().Model(&User{}).
		Where("id = ? AND is_deleted = 0", userId).
		Updates(updateData)

	if result.Error != nil {
		// 处理唯一约束错误
		if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
			return 0, errors.New("唯一约束冲突")
		}
	}

	if result.RowsAffected == 0 {
		return 0, errors.New("用户不存在或已被删除")
	}

	return result.RowsAffected, nil
}

// EditPassword 修改用户密码
func EditPassword(query UserPassword, userId string) error {

	hashPassword, bcryptErr := bcrypt.GenerateFromPassword([]byte(query.Password), bcrypt.DefaultCost)
	if bcryptErr != nil {
		return bcryptErr
	}
	err := dao.Db.Debug().Table("users").
		Where("is_deleted = 0").
		Where("id = ?", userId).
		Updates(map[string]interface{}{"password": string(hashPassword)}).Error
	return err
}

// ----------------- 以下旧代码 ----------------------
//
//// GetUserWithRole 根据用户名查询用户、角色信息、用户密码
//func GetUserWithRole(query LoginRequest) (*UserWithRole, error) {
//	var result UserWithRole
//
//	err := dao.Db.Debug().Table("sys_user t1").
//		Select("t1.id AS userId, t1.username, t1.nickname, t1.password, t1.status, t1.dept_id").
//		Joins("LEFT JOIN sys_user_role t2 ON t2.user_id = t1.id").
//		Joins("LEFT JOIN sys_role t3 ON t3.id = t2.role_id").
//		Where("t1.username = ? AND t1.is_deleted = ?", query.Username, 0).
//		Group("t1.id, t1.username, t1.nickname, t1.password, t1.status, t1.dept_id").
//		Scan(&result).Error
//
//	if err != nil {
//		return nil, err
//	}
//	return &result, nil
//}
//
//// GetUserFormInfoById 根据id获取用户表单数据
//func GetUserFormInfoById(userId string) (*SysUserUsersFormSelect, error) {
//	var result SysUserUsersFormSelect
//	//SELECT id, username, nickname, mobile, gender, avatar, email, status, dept_id
//	//FROM sys_user
//	//WHERE id = ? AND is_deleted = 0
//
//	err := dao.Db.Debug().Table("sys_user").
//		Select("id, username, nickname, mobile, gender, avatar, email, status, dept_id ").
//		Where("id = ? AND is_deleted = 0", userId).
//		Scan(&result).Error
//
//	if err != nil {
//		return nil, err
//	}
//	return &result, nil
//}
//
//// GetUserProfile  根据用户ID获取用户信息UserProfile
//func GetUserProfile(id string) (*UserProfile, error) {
//
//	var result UserProfile
//	//SELECT id, username, nickname, avatar FROM sys_user
//	//WHERE is_deleted = 0 AND (username = ?)
//	err := dao.Db.Debug().Table("sys_user").
//		Where("is_deleted = 0 AND (id = ?)", id).
//		Scan(&result).Error
//
//	if err != nil {
//		return nil, err
//	}
//	return &result, nil
//}
//
//// GetUserPageList 获取用户分页列表相关数据
//func GetUserPageList(query SysUserUsersPageListParams, pageParams PaginationParams) ([]SysUserUsersPageListSelect, int64, int, int, error) {
//
//	var users []SysUserUsersPageListSelect
//	var total int64
//	rootDeptID := 1
//
//	// 创建子查询用于获取部门ID列表
//	deptSubQuery := dao.Db.Table("sys_dept").Select("id").Where("id = ? OR FIND_IN_SET(?, tree_path)", rootDeptID, rootDeptID)
//
//	// 主查询用于获取分页数据
//	model := dao.Db.Debug().Table("sys_user u").
//		Select("u.id, u.username, u.nickname, u.mobile, u.gender, u.email,u.avatar, u.status, d.name AS dept_name, GROUP_CONCAT(r.name) AS role_names, u.create_time").
//		Joins("LEFT JOIN sys_dept d ON u.dept_id = d.id").
//		Joins("LEFT JOIN sys_user_role sur ON u.id = sur.user_id").
//		Joins("LEFT JOIN sys_role r ON sur.role_id = r.id").
//		Where("u.is_deleted = 0").
//		Where("u.username != ?", "root").
//		Where("u.dept_id IN (?)", deptSubQuery).
//		Group("u.id")
//
//	// 如果传入了查询条件，则加入模糊查询
//	if query.Keywords != "" {
//		model = model.Where("u.username LIKE ? OR u.nickname LIKE ? OR u.mobile LIKE ?", "%"+query.Keywords+"%", "%"+query.Keywords+"%", "%"+query.Keywords+"%")
//	}
//
//	if query.DeptID != "" {
//		model = model.Where("concat(',', concat(d.tree_path, ',', d.id), ',') LIKE concat('%,', ?, ',%')", query.DeptID)
//	}
//
//	if query.Status != "" {
//		model = model.Where("u.status = ?", query.Status)
//	}
//
//	if query.StartTime != "" && query.EndTime != "" {
//		model = model.Where("u.create_time >= ? AND u.create_time <= ?", query.StartTime, query.EndTime)
//	}
//
//	// 获取总记录数
//	if err := model.Count(&total).Error; err != nil {
//		return nil, 0, 0, 0, err
//	}
//	fmt.Println("-------")
//
//	fmt.Println(total)
//	fmt.Println("-------")
//	// 添加分页条件
//	offset := (pageParams.PageNum - 1) * pageParams.PageSize
//	model = model.Limit(pageParams.PageSize).Offset(offset)
//
//	// 执行查询获取分页数据
//	if err := model.Scan(&users).Error; err != nil {
//		return nil, 0, 0, 0, err
//	}
//
//	return users, total, pageParams.PageNum, pageParams.PageSize, nil
//
//}
//
//// AddUser 新增用户
//func AddUser(user SysUserAddParams) (int64, error) {
//	var insertData SysUserAddData
//
//	cpErr := copier.Copy(&insertData, &user)
//	if cpErr != nil {
//		return insertData.ID, cpErr
//	}
//
//	insertData.CreateTime = time.Now()
//	insertData.UpdateTime = time.Now()
//	// 增加默认密码 123456
//	hashPassword, bcryptErr := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.DefaultCost)
//	if bcryptErr != nil {
//		return 0, bcryptErr
//	}
//	// 加密后的密码同步到用户信息中
//	insertData.Password = string(hashPassword)
//
//	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
//	err := dao.Db.Table("sys_user").Create(&insertData).Error // 通过数据的指针来创建
//	return insertData.ID, err
//}
//
//// EditUser 修改用户
//func EditUser(user SysUserEditParams, userId string) error {
//	var editData SysUserEditData
//
//	cpErr := copier.Copy(&editData, &user)
//	if cpErr != nil {
//		return cpErr
//	}
//
//	editData.UpdateTime = time.Now()
//
//	fmt.Printf("editData: %+v\n", editData)
//
//	err := dao.Db.Debug().Table("sys_user").
//		Select("username", "nickname", "gender", "dept_id", "mobile", "status", "email", "update_time").
//		Where("is_deleted = 0").
//		Where("id = ?", userId).
//		Updates(&editData).Error
//
//	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
//	return err
//}
//
//// DelUsers 批量删除（硬删除）
//func DelUsers(ids string) error {
//
//	// UPDATE sys_user SET update_time = ?, is_deleted = 1 WHERE id = ? AND is_deleted = 0
//
//	var idsArr []SysUserId
//	for _, val := range strings.Split(ids, ",") {
//		valNew, _ := strconv.ParseInt(val, 10, 64)
//		idsArr = append(idsArr, SysUserId{
//			ID: valNew,
//		})
//	}
//	err := dao.Db.Debug().Table("sys_user").Delete(&idsArr).Error
//	return err
//}
//
//// DelUsersSoft 批量删除（软删除）
//func DelUsersSoft(ids string) error {
//
//	// UPDATE sys_user SET update_time = ?, is_deleted = 1 WHERE id = ? AND is_deleted = 0
//	err := dao.Db.Debug().Table("sys_user").
//		Where("is_deleted = 0").
//		Where("id IN (?)", ids).
//		Updates(map[string]interface{}{"update_time": time.Now(), "is_deleted": 1}).Error
//	return err
//}
//
//// EditPassword 修改用户密码
//func EditPassword(query SysUserPassword, userId string) error {
//
//	hashPassword, bcryptErr := bcrypt.GenerateFromPassword([]byte(query.Password), bcrypt.DefaultCost)
//	if bcryptErr != nil {
//		return bcryptErr
//	}
//	err := dao.Db.Debug().Table("sys_user").
//		Where("is_deleted = 0").
//		Where("id = ?", userId).
//		Updates(map[string]interface{}{"password": string(hashPassword)}).Error
//	return err
//}
//
//// EditStatus 修改用户状态
//func EditStatus(query SysUserStatus, userId string) error {
//
//	err := dao.Db.Debug().Table("sys_user").
//		Where("is_deleted = 0").
//		Where("id = ?", userId).
//		Updates(map[string]interface{}{"status": query.Status}).Error
//	return err
//}
//
//// EditUserProfile 修改个人中心用户信息
//func EditUserProfile(user *UserProfile, userId string) error {
//	//var editData UserProfile
//
//	//cpErr := copier.Copy(&editData, &user)
//	//if cpErr != nil {
//	//	return cpErr
//	//}
//
//	//editData.UpdateTime = time.Now()
//
//	err := dao.Db.Debug().Table("sys_user").
//		Where("is_deleted = 0").
//		Where("id = ?", userId).
//		Updates(user).Error
//
//	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
//	return err
//}
//
//// --- 旧代码---
//
//// AddUsers 批量增加用户
//func AddUsers(users *[]PUser) ([]uint64, error) {
//
//	fmt.Println(*users)
//
//	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
//	err := dao.Db.Create(users).Error // 通过数据的指针来创建
//	var insertIds []uint64
//	for _, user := range *users {
//		insertIds = append(insertIds, uint64(user.ID)) // 1,2,3
//	}
//
//	return insertIds, err
//}
//
//// SaveUser 保存所有字段
//func SaveUser(user *PUser) (uint64, error) {
//	//Create参数需要传入一个指针，所有形参user定义为结构体指针类型
//	err := dao.Db.Save(user).Error // 通过数据的指针来创建
//	return uint64(user.ID), err
//}
